package com.tdrc.common.service;

import com.tdrc.common.beans.Menu;
import com.tdrc.common.beans.Unit;
import com.tdrc.common.mapper.UnitMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author dpf
 * @version 1.0
 * @date 2020-5-19 15:15
 * @instruction ...
 */
@Service
public class UnitService implements IUnitService {
    @Resource
    private UnitMapper unitMapper;


    @Override
    public void addUnit(Unit unit) {
        unitMapper.addUnit(unit);
    }

    @Override
    public void updateUnit(Unit unit) {
      unitMapper.updateUnit(unit);
    }

    @Override
    public void deleteUnit(Integer unitId) {
        unitMapper.deleteUnit(unitId);
    }

    @Override
    public List<Unit> treeUnit(Integer unitId) {

        return getChildren(unitId);
    }

    @Override
    public List<Map<String, Object>> listUnit() {
        return unitMapper.listUnit();
    }

    /**
     * 递归生成树级单位数据
     * @param unitId
     * @return
     */
    public List<Unit> getChildren(Integer unitId){
        List<Unit> treeUnit = new ArrayList<Unit>();
        List<Unit> children = unitMapper.getChildren(unitId);
        for(Unit unit : children){
            if(!this.getChildren(unit.getUnitId()).isEmpty()){
                unit.setChildren(this.getChildren(unit.getUnitId()));
            }
            treeUnit.add(unit);
        }
        return treeUnit;
    }
}
